import $on from '~/lib/on.coffee'
import ipc from '~/lib/ipc.coffee'
import platform from '@/config/platform.mjs'

{drag:{setBounds,getBounds}} = ipc
pointermove = 'pointermove'
IGNORE = new Set('SELECT BUTTON A INPUT TEXTAREA'.split ' ')
{round} = Math
export default main = (elem)=>
  if platform!='win32'
    return

  elem.style.appRegion = 'no-drag'

  moving = false

  _move = =>

  down = (e)=>
    if moving
      return
    if e.button!=0 # 鼠标左键
      return
    {target} = e
    p = e.target
    loop
      {nodeName} = p
      if IGNORE.has nodeName
        return
      if nodeName == 'BODY'
        break
      p = p.parentNode
    moving = true
    {screenX:init_x,screenY:init_y} = e


    {
      x:init_left
      y:init_top
      height:init_h
      width:init_w
    } = await getBounds()
    _move = (e)=>
      {screenX,screenY} = e
      setBounds(
        round screenX-init_x+init_left
        round screenY-init_y+init_top
        init_w
        init_h
      )
      return
    elem.setPointerCapture e.pointerId
    elem.addEventListener pointermove,_move
    return

  up = (e)=>
    if moving
      await _move(e)
      elem.releasePointerCapture e.pointerId
      elem.removeEventListener pointermove,_move
      _move = =>
      moving = false
    return

  $on elem,{
    lostpointercapture:up
    pointercancel:up
    pointerdown:down
    pointerup:up
  }

  return
